<template>
  <div class="tinymce-body" @click.stop="handleClick">
    <editor
      v-model="value"
      :disabled="readOnly"
      class="editor-box"
      api-key="no-api-key"
      :init="{
        menubar: false,
        inline: true,
        plugins: [
          'advlist autolink lists image charmap print preview anchor',
          'searchreplace visualblocks code fullscreen noneditable',
          'insertdatetime media table paste code help wordcount',
        ],
        noneditable_noneditable_class: 'mceNonEditable',
        toolbar_location: 'top',
        fixed_toolbar_container: `.${id}`,
        toolbar_sticky: true,
        toolbar: [
          {
            name: 'formatting',
            items: ['bold', 'italic', 'underline'],
          },
          {
            name: 'styles',
            items: ['fontselect', 'fontsizeselect'],
          },
          {
            name: 'color',
            items: ['forecolor', 'backcolor'],
          },
          {
            name: 'alignment',
            items: ['alignleft', 'aligncenter', 'alignright', 'alignjustify'],
          },
          {
            name: 'indentation',
            items: ['bullist', 'numlist', 'outdent', 'indent'],
          },
          {
            name: 'history',
            items: ['undo', 'redo'],
          },
        ],
        font_formats:
          'Andale Mono=andale mono,times; Arial=arial,helvetica,sans-serif; Book Antiqua=book antiqua,palatino; Comic Sans MS=comic sans ms,sans-serif; Courier New=courier new,courier; Helvetica=helvetica; Impact=impact,chicago; Tahoma=tahoma,arial,helvetica,sans-serif; Terminal=terminal,monaco; Times New Roman=times new roman,times; Trebuchet MS=trebuchet ms,geneva; Verdana=verdana,geneva; Wingdings=wingdings,zapf dingbats',
      }"
      @onBlur="handleBlur"
      @onFocus="showFormula"
      @onClick="handleFormulaClick"
      @onChange="handleTextChange"
      @onKeydown="handleKeyDown"
      @onSetContent="handleSetContent"
    />
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import { Editor } from '@/components/common/tinymce/tinymce-editor'

@Component({
  components: {
    Editor,
  },
})
export default class TextEditor extends Vue {
  @Prop({
    type: String,
    default() {
      return ''
    },
  })
  textValue: String | undefined
  //  locate parent element
  @Prop({
    type: String,
    default() {
      return ''
    },
  })
  id?: String
  //  used in preivew/publish mode
  @Prop({
    type: Boolean,
    default() {
      return false
    },
  })
  readOnly?: boolean

  // 目前问题，多个文本组件，均显示在第一个box 中
  private value: any = ''
  private time: number = 0 //  track first blur status

  public mounted() {
    this.value = this.textValue
    //  for init render formula result
    setTimeout(() => {
      if (this.readOnly) {
        this.showResult()
      }
      this.$emit('render-complete')
    }, 500)
  }

  @Watch('textValue')
  handleTextValue(newValue: any) {
    this.value = newValue
  }

  public handleClick() {
    this.$emit('handle-click')
  }

  public handleBlur() {
    //  fix first time render result issue
    if (this.time === 0) {
      setTimeout(() => {
        this.showResult()
      }, 200)
    } else {
      this.showResult()
    }
    this.time += 1
  }

  public showResult() {
    const elements = document.querySelectorAll(`.${this.id} .formula-style`)

    if (elements.length > 0) {
      //  replace text with data-result value with innerText
      //  remove .formula-style, add result-style
      elements.forEach((item: any) => {
        item.textContent = item.getAttribute('data-result')
        item.classList.remove('formula-style')
        item.classList.add('result-style')
      })
    }
    this.$emit('editor-blur')
  }

  public showFormula() {
    const elements = document.querySelectorAll(`.${this.id} .result-style`)

    if (elements.length > 0) {
      //  replace text with data-result value with innerText
      //  remove .formula-style, add result-style
      elements.forEach((item: any) => {
        item.textContent = item.getAttribute('data-formula')
        item.classList.add('formula-style')
        item.classList.remove('result-style')
      })
    }
  }

  public handleFormulaClick(element: any) {
    if (element.target.className.includes('formula-style')) {
      this.$emit('highlight-formula', element.target.getAttribute('data-id'))
    }
  }

  public handleTextChange() {
    this.$emit('text-change', this.value)
  }

  //  remove error border after delete the ERROR target
  public handleKeyDown(event: any, editor: any) {
    if (event.which === 8 || event.keyCode === 8) {
      //  watch Backspace key
      // Backspace key
      const element = document.querySelectorAll(`.${this.id} .error-style`)
      if (element.length === 0) {
        this.$emit('remove-error-border')
      }
    }
    if (event.which === 13 || event.keyCode === 13) {
      //  watch enter key
      editor.selection
        .getNode()
        .scrollIntoView({ behavior: 'auto', block: 'center', inline: 'center' })
    }
  }

  //  for update / delete formula content
  public handleSetContent(event: Event, editor: any) {
    //  update value & textValue
    this.value = editor.getContent()
    this.$emit('text-change', this.value)

    const element = document.querySelectorAll(`.${this.id} .error-style`)
    if (element.length > 0) {
      this.$emit('add-error-border')
    } else {
      this.$emit('remove-error-border')
    }
  }
}
</script>

<style lang="less" scoped>
.tinymce-body {
  height: 100%;
  padding: 8px 25px;
}

.editor-box {
  height: 100%;
  margin-top: 20px;
  outline: none;
  overflow-y: scroll;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(144, 147, 153, 0.5);
    border-radius: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
    border-radius: 5px;
  }
}

/deep/ .error-style {
  color: #e6505a;
}
</style>
